package cn.wolfcode.wms.service.impl;

import cn.wolfcode.wms.domain.Role;
import cn.wolfcode.wms.mapper.RoleMapper;
import cn.wolfcode.wms.qo.QueryObject;
import cn.wolfcode.wms.service.IRoleService;
import cn.wolfcode.wms.util.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.swing.text.html.Option;
import java.util.List;
import java.util.Optional;

@Service
public class RoleServiceImpl implements IRoleService {
    @Autowired
    private RoleMapper roleMapper;

    @Override
    public void saveOrUpdate(Role entity, Long[] permissionIds,Long[] menuIds) {
        if (!Optional.ofNullable(entity.getId()).isPresent()) {
            roleMapper.insert(entity);
        }else {
            //先删除关系
            roleMapper.deleteMenuRelation(entity.getId());
            roleMapper.deleteRelation(entity.getId());
            roleMapper.updateByPrimaryKey(entity);
        }
        if (Optional.ofNullable(permissionIds).isPresent()) {
            for (Long permissionId : permissionIds) {
                roleMapper.insertRelation(entity.getId(),permissionId);
            }
        }
        if (Optional.ofNullable(menuIds).isPresent()) {
            for (Long menuId : menuIds) {
                roleMapper.insertMenuRelation(entity.getId(),menuId);
            }
        }
    }

    @Override
    public void delete(Long id) {
        roleMapper.deleteMenuRelation(id);
        roleMapper.deleteRelation(id);
        roleMapper.deleteByPrimaryKey(id);
    }

    @Override
    public Role get(Long id) {
        return roleMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Role> list() {
        return roleMapper.selectAll();
    }

    @Override
    public PageResult query(QueryObject qo) {
        Integer rows = roleMapper.selectForCount(qo);
        if (rows == 0){
            return PageResult.EMPTY_PAGE;
        }
        List<Role> list = roleMapper.selectForList(qo);
        PageResult result = new PageResult(qo.getCurrentPage(),qo.getPageSize(),rows,list);
        return result;
    }
}
